package com.xbq.oauth.social.qq.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;

import java.io.IOException;


@Slf4j
public class QQImpl extends AbstractOAuth2ApiBinding implements QQ {

    //获取openId的URL
    private static final String URL_GET_OPEN_ID = "https://graph.qq.com/oauth2.0/me?access_token=%s";

    //获取用户信息地址
    private static final String URL_GET_USER_INFO = "https://graph.qq.com/user/get_user_info?\n" +
            "oauth_consumer_key=%s&" + "openid=%s";

    private ObjectMapper objectMapper = new ObjectMapper();

    private String appId;
    private String openId;

    public QQImpl(String accessToken, String appId){
        //调用父类的构造方法，把accessToken放到请求的参数中
        super(accessToken, TokenStrategy.ACCESS_TOKEN_PARAMETER);
        this.appId = appId;

        String url = String.format(URL_GET_OPEN_ID,accessToken);
        //callback( {"client_id":"YOUR_APPID","openid":"YOUR_OPENID"} );
        String result = getRestTemplate().getForObject(url,String.class);
        log.info(result);

        this.openId = StringUtils.substringBetween(result,"\"openid\":", "}");
    }

    @Override
    public QQUserInfo getQQUserInfo(){
        String url = String.format(URL_GET_USER_INFO,appId,openId);
        String result = getRestTemplate().getForObject(url,String.class);
        log.info(result);
        QQUserInfo userInfo = null;
        try {
            userInfo = objectMapper.readValue(result,QQUserInfo.class);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return userInfo;
    }
}
